from rest_framework import serializers
from .models import (
    AIProvider, AIModel, AIRole, AIConversation, 
    AIMessage, TokenUsageLog, MessageTemplate, UserFavorite
)


class AIProviderSerializer(serializers.ModelSerializer):
    """AI提供商序列化器"""
    
    class Meta:
        model = AIProvider
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owner']
    
    def to_representation(self, instance):
        """自定义序列化输出，隐藏敏感信息"""
        data = super().to_representation(instance)
        # 脱敏API密钥
        if 'api_key' in data and data['api_key']:
            data['api_key'] = '****' + data['api_key'][-4:] if len(data['api_key']) > 4 else '****'
        return data


class AIProviderCreateSerializer(serializers.ModelSerializer):
    """AI提供商创建序列化器"""
    
    class Meta:
        model = AIProvider
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owner']
    
    def validate_api_key(self, value):
        """验证API密钥格式"""
        if not value or len(value.strip()) < 10:
            raise serializers.ValidationError("API密钥长度不能少于10个字符")
        return value.strip()
    
    def validate_api_endpoint(self, value):
        """验证API端点格式"""
        if not value.startswith(('http://', 'https://')):
            raise serializers.ValidationError("API端点必须以http://或https://开头")
        return value


class AIModelSerializer(serializers.ModelSerializer):
    """AI模型序列化器"""
    provider_name = serializers.CharField(source='provider.name', read_only=True)
    
    class Meta:
        model = AIModel
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by']
    
    def validate_max_tokens(self, value):
        """验证最大Token数"""
        if value <= 0:
            raise serializers.ValidationError("最大Token数必须大于0")
        if value > 200000:
            raise serializers.ValidationError("最大Token数不能超过200000")
        return value


class AIRoleSerializer(serializers.ModelSerializer):
    """AI角色序列化器"""
    creator_name = serializers.CharField(source='created_by.username', read_only=True)
    
    class Meta:
        model = AIRole
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by', 'usage_count']
    
    def validate_system_prompt(self, value):
        """验证系统提示词"""
        if not value or len(value.strip()) < 10:
            raise serializers.ValidationError("系统提示词长度不能少于10个字符")
        if len(value) > 10000:
            raise serializers.ValidationError("系统提示词长度不能超过10000个字符")
        return value.strip()


class AIConversationSerializer(serializers.ModelSerializer):
    """AI对话会话序列化器"""
    owner_name = serializers.CharField(source='owner.username', read_only=True)
    ai_model_name = serializers.CharField(source='ai_model.name', read_only=True)
    ai_role_name = serializers.CharField(source='ai_role.name', read_only=True)
    message_count = serializers.SerializerMethodField()
    
    class Meta:
        model = AIConversation
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by',
                           'owner', 'used_tokens', 'last_message_at']
    
    def get_message_count(self, obj):
        """获取消息数量"""
        return obj.messages.count()
    
    def validate_title(self, value):
        """验证会话标题"""
        if not value or len(value.strip()) < 1:
            raise serializers.ValidationError("会话标题不能为空")
        if len(value) > 200:
            raise serializers.ValidationError("会话标题长度不能超过200个字符")
        return value.strip()


class AIMessageSerializer(serializers.ModelSerializer):
    """AI消息序列化器"""
    ai_role_name = serializers.CharField(source='ai_role.name', read_only=True)
    is_user_message = serializers.BooleanField(read_only=True)
    context_position = serializers.SerializerMethodField()
    estimated_tokens = serializers.SerializerMethodField()

    class Meta:
        model = AIMessage
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by', 'token_count']

    def get_context_position(self, obj):
        """获取消息在对话中的位置"""
        return obj.conversation.messages.filter(
            created_at__lt=obj.created_at
        ).count() + 1

    def get_estimated_tokens(self, obj):
        """获取估算的Token数量"""
        if obj.token_count:
            return obj.token_count

        # 简单估算
        content = obj.content or ""
        chinese_chars = len([c for c in content if '\u4e00' <= c <= '\u9fff'])
        other_chars = len(content) - chinese_chars
        return chinese_chars + (other_chars // 4)

    def validate_content(self, value):
        """验证消息内容"""
        if not value or len(value.strip()) < 1:
            raise serializers.ValidationError("消息内容不能为空")
        if len(value) > 50000:
            raise serializers.ValidationError("消息内容长度不能超过50000个字符")
        return value.strip()


class TokenUsageLogSerializer(serializers.ModelSerializer):
    """Token使用记录序列化器"""
    user_name = serializers.CharField(source='user.username', read_only=True)
    ai_model_name = serializers.CharField(source='ai_model.name', read_only=True)
    conversation_title = serializers.CharField(source='conversation.title', read_only=True)
    
    class Meta:
        model = TokenUsageLog
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by', 'total_tokens']


class MessageTemplateSerializer(serializers.ModelSerializer):
    """消息模板序列化器"""
    owner_name = serializers.CharField(source='owner.username', read_only=True)
    
    class Meta:
        model = MessageTemplate
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owner', 'usage_count']
    
    def validate_content(self, value):
        """验证模板内容"""
        if not value or len(value.strip()) < 1:
            raise serializers.ValidationError("模板内容不能为空")
        if len(value) > 10000:
            raise serializers.ValidationError("模板内容长度不能超过10000个字符")
        return value.strip()


class UserFavoriteSerializer(serializers.ModelSerializer):
    """用户收藏序列化器"""
    owner_name = serializers.CharField(source='owner.username', read_only=True)
    conversation_title = serializers.CharField(source='conversation.title', read_only=True)
    
    class Meta:
        model = UserFavorite
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by', 'updated_by', 'owner']
    
    def validate(self, data):
        """验证收藏对象"""
        conversation = data.get('conversation')
        message = data.get('message')
        
        if not conversation and not message:
            raise serializers.ValidationError("必须指定收藏的会话或消息")
        
        if conversation and message:
            # 验证消息是否属于指定会话
            if message.conversation != conversation:
                raise serializers.ValidationError("消息不属于指定的会话")
        
        return data


# 操作相关的序列化器

class AIProviderTestSerializer(serializers.Serializer):
    """AI提供商连接测试序列化器"""
    provider_id = serializers.IntegerField(help_text="提供商ID")
    test_message = serializers.CharField(
        default="Hello, this is a test message.",
        help_text="测试消息内容"
    )


class ConversationCreateSerializer(serializers.Serializer):
    """创建对话会话序列化器"""
    title = serializers.CharField(max_length=200, help_text="会话标题")
    ai_model_id = serializers.IntegerField(help_text="AI模型ID")
    ai_role_id = serializers.IntegerField(required=False, help_text="AI角色ID")


class MessageSendSerializer(serializers.Serializer):
    """发送消息序列化器"""
    content = serializers.CharField(help_text="消息内容")
    parent_message_id = serializers.IntegerField(required=False, help_text="父消息ID")
    include_context = serializers.BooleanField(
        default=True,
        help_text="是否包含上下文记忆"
    )
    context_limit = serializers.IntegerField(
        default=10,
        min_value=1,
        max_value=50,
        help_text="上下文消息数量限制"
    )
    max_context_tokens = serializers.IntegerField(
        default=120000,
        min_value=1000,
        max_value=200000,
        help_text="上下文最大Token数限制"
    )

    def validate_content(self, value):
        """验证消息内容"""
        if not value or len(value.strip()) < 1:
            raise serializers.ValidationError("消息内容不能为空")
        if len(value) > 50000:
            raise serializers.ValidationError("消息内容长度不能超过50000个字符")
        return value.strip()


class BatchOperationSerializer(serializers.Serializer):
    """批量操作序列化器"""
    ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="对象ID列表"
    )
    operation = serializers.ChoiceField(
        choices=['delete', 'archive', 'activate', 'deactivate'],
        help_text="操作类型"
    )


class TokenUsageStatsSerializer(serializers.Serializer):
    """Token使用统计序列化器"""
    total_tokens = serializers.IntegerField(help_text="总Token数")
    input_tokens = serializers.IntegerField(help_text="输入Token数")
    output_tokens = serializers.IntegerField(help_text="输出Token数")
    total_cost = serializers.DecimalField(max_digits=10, decimal_places=6, help_text="总成本")
    period = serializers.CharField(help_text="统计周期")
    model_breakdown = serializers.DictField(help_text="按模型分解的统计")


class ConversationExportSerializer(serializers.Serializer):
    """对话导出序列化器"""
    format = serializers.ChoiceField(
        choices=['json', 'txt', 'markdown'],
        default='json',
        help_text="导出格式"
    )
    include_metadata = serializers.BooleanField(
        default=False,
        help_text="是否包含元数据"
    )


class ConversationContextSerializer(serializers.Serializer):
    """对话上下文序列化器"""
    conversation_id = serializers.IntegerField(help_text="会话ID")
    message_limit = serializers.IntegerField(
        default=10,
        min_value=1,
        max_value=50,
        help_text="消息数量限制"
    )
    token_limit = serializers.IntegerField(
        default=120000,
        min_value=1000,
        max_value=200000,
        help_text="Token数量限制"
    )
    include_system_prompt = serializers.BooleanField(
        default=True,
        help_text="是否包含系统提示词"
    )


class MessageContextSerializer(serializers.Serializer):
    """消息上下文序列化器 - 用于返回上下文信息"""
    role = serializers.CharField(help_text="角色类型: system/user/assistant")
    content = serializers.CharField(help_text="消息内容")
    token_count = serializers.IntegerField(help_text="Token数量")
    created_at = serializers.DateTimeField(help_text="创建时间")


class ConversationContextResponseSerializer(serializers.Serializer):
    """对话上下文响应序列化器"""
    conversation_id = serializers.IntegerField(help_text="会话ID")
    total_messages = serializers.IntegerField(help_text="总消息数")
    context_messages = serializers.ListField(
        child=MessageContextSerializer(),
        help_text="上下文消息列表"
    )
    total_tokens = serializers.IntegerField(help_text="总Token数")
    system_prompt = serializers.CharField(
        required=False,
        help_text="系统提示词"
    )
    window_size = serializers.IntegerField(help_text="滑动窗口大小")


class AIResponseSerializer(serializers.Serializer):
    """AI响应序列化器"""
    message_id = serializers.IntegerField(help_text="消息ID")
    content = serializers.CharField(help_text="AI回复内容")
    token_usage = serializers.DictField(help_text="Token使用情况")
    model_info = serializers.DictField(help_text="模型信息")
    response_time = serializers.FloatField(help_text="响应时间(秒)")
    context_used = serializers.BooleanField(help_text="是否使用了上下文")
    context_token_count = serializers.IntegerField(
        default=0,
        help_text="上下文Token数量"
    )
